#!/usr/bin/env python
#
# Copyright 2015 Time-My-Life team (NSC 2015).
#
import webapp2
import json
import random
import logging
from dbase import *


class RegisterHandler(webapp2.RequestHandler):
    def get(self):
        ''' Generate ID using additive random number '''
        try:
            # 1. extract 'id' parameter as integer
            id = int(self.request.get('id'))
            # 2. generate random number 0-4999 and add to <id>
            num = int(random.random()*5000)
            # 3. generate Account and put into Datastore
            new_id = id+num
            new_account = Account(id=new_id)
            new_account.put()        
            # 4. create JSON response with 'OK' status
            resp = {'status':'OK', 'id':new_id} 
            logging.info('Register ID: %d'%id)
        except:
            # 5. create JSON response with 'ERROR' status
            resp = {'status':'ERROR'}
            
            logging.debug('Wrong ID parameter')        
        self.response.write(json.dumps(resp))

app = webapp2.WSGIApplication([
    ('/register', RegisterHandler)
], debug=True)